/*
 * BlockPersistor.cpp
 *
 */

#include "BlockPersistor.h"
#include "../log/Logger.h"
#include "../utils/Utils.h"

BlockPersistor::BlockPersistor(BigInt size, float capacity) : data(size), serializer(data), unserializer(data) {
	dataLimit = capacity*size;
}

BlockPersistor::~BlockPersistor() {

}

void BlockPersistor::clear() {
	serializer.setOffset(0);
	unserializer.setOffset(0);
}

bool BlockPersistor::serialize(const ISerializable& serializable) {
	if (serializer.getOffset() + serializable.size() > dataLimit)
		return false;
	serializable.serialize(serializer);
	return true;
}

bool BlockPersistor::unserialize(ISerializable& serializable) {
	serializable.unserialize(unserializer);
	return true;
}

BigInt BlockPersistor::size() const {
	return data.size();
}

bool BlockPersistor::save(std::fstream& file) {
	file.write((char*)&data[0], data.size());
	file.flush();
	if (file.fail()) {
		file.clear();
		return false;
	}
	return true;
}

bool BlockPersistor::load(std::fstream& file) {
	file.read((char*)&data[0], data.size());
	unserializer.move(0);
	if (file.fail()) {
		file.clear();
		return false;
	}
	return true;
}




